package com.zw.cloud.mybatis.plus.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.zw.cloud.common.utils.DingTalkUtils;
import com.zw.cloud.mybatis.plus.entity.Tc;
import com.zw.cloud.mybatis.plus.entity.vo.TcResultVO;
import com.zw.cloud.mybatis.plus.mapper.TcMapper;
import com.zw.cloud.mybatis.plus.service.api.ITcService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zw
 * @since 2022-08-14
 */
@Service
public class TcServiceImpl extends ServiceImpl<TcMapper, Tc> implements ITcService {

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public List<Tc> queryTcListFromRemote(int pageNo) {
        String url = "https://webapi.sporttery.cn/gateway/lottery/getHistoryPageListV1.qry?gameNo=85&provinceId=0&pageSize=30&isVerify=1&pageNo=" + pageNo;
        String result = restTemplate.getForObject(url, String.class);
        TcResultVO tcResultVO = JSON.parseObject(result, TcResultVO.class);
        TcResultVO.ResultValue value = tcResultVO.getValue();
        List<Tc> tcList = new ArrayList<>();
        if (Objects.isNull(value)) {
            return tcList;
        }
        List<TcResultVO.ValueData> list = value.getList();
        if (CollectionUtils.isEmpty(list)) {
            return tcList;
        }
        for (TcResultVO.ValueData valueData : list) {
            String lotteryDrawResult = valueData.getLotteryDrawResult();
            String[] values = lotteryDrawResult.split(" ");
            Tc tc = new Tc();
            tc.setId(valueData.getLotteryDrawNum());
            tc.setOne(Integer.valueOf(values[0]));
            tc.setTwo(Integer.valueOf(values[1]));
            tc.setThree(Integer.valueOf(values[2]));
            tc.setFour(Integer.valueOf(values[3]));
            tc.setFive(Integer.valueOf(values[4]));
            tc.setSix(Integer.valueOf(values[5]));
            tc.setSeven(Integer.valueOf(values[6]));
            tcList.add(tc);
        }
        return tcList;
    }

    @Override
    public void sendTcMsg(Integer count) {
        List<Tc> tcList = queryTcListFromRemote(1);
        if (CollectionUtils.isEmpty(tcList)) {
            return;
        }
        tcList = tcList.subList(0, count);
        tcList.sort(Comparator.comparing(Tc::getId));
        StringBuilder msg = new StringBuilder("TC最近开奖: \n\n");
        for (Tc tc : tcList) {
            msg.append(tc.getId()).append("  ")
                    .append("<font color=#FF0000>")
                    .append(String.format("%02d",tc.getOne())).append(" ")
                    .append(String.format("%02d",tc.getTwo())).append(" ")
                    .append(String.format("%02d",tc.getThree())).append(" ")
                    .append(String.format("%02d",tc.getFour())).append(" ")
                    .append(String.format("%02d",tc.getFive()))
                    .append("</font>").append(" ")
                    .append("<font color=#0000FF>")
                    .append(String.format("%02d",tc.getSix())).append(" ")
                    .append(String.format("%02d",tc.getSeven()))
                    .append("</font>").append(" ")
                    .append("\n\n");
        }
        Set<Integer> redSet = new HashSet<>();
        while (redSet.size() < 5) {
            Random random = new Random();
            int blue = random.nextInt(35);
            if (blue > 0) {
                redSet.add(blue);
            }
        }
        Set<Integer> blueSet = new HashSet<>();
        while (blueSet.size() < 2) {
            Random random = new Random();
            int blue = random.nextInt(12);
            if (blue > 0) {
                blueSet.add(blue);
            }
        }
        List<Integer> redList = Lists.newArrayList(redSet).stream().sorted(Comparator.comparing(s -> s)).collect(Collectors.toList());
        msg.append("<font color=#FF0000>").append(redList.stream().map(String::valueOf).collect(Collectors.joining(" ")))
                .append("</font>").append("  ")
                .append("<font color=#0000FF>").append(Lists.newArrayList(blueSet).stream().sorted(Comparator.comparing(s -> s))
                        .map(String::valueOf).collect(Collectors.joining(" ")))
                .append("</font>").append("\n\n");

        DingTalkUtils.sendDingTalkMsgWithSign("TC",msg.toString());
    }

    @Override
    public Map<String, List<Integer>> queryFcList(Integer count) {
        LambdaQueryWrapper<Tc> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Tc::getId).last("limit " + count);
        List<Tc> tcList = list(queryWrapper);
        Set<Integer> codeSet = new HashSet<>(30);
        tcList.forEach(tc -> {
            codeSet.add(tc.getOne());
            codeSet.add(tc.getTwo());
            codeSet.add(tc.getThree());
            codeSet.add(tc.getFour());
            codeSet.add(tc.getFive());
        });
        Set<Integer> allCodeSet = new HashSet<>(35);
        for (int i = 1; i <= 35; i++) {
            allCodeSet.add(i);
        }
        List<Integer> exitList = codeSet.stream().sorted().collect(Collectors.toList());
        Sets.SetView<Integer> difference = Sets.difference(allCodeSet, codeSet);
        Set<Integer> blueSet = tcList.stream().flatMap(tc -> Stream.of(tc.getSix(), tc.getSeven())).collect(Collectors.toSet());
        List<Integer> notExitList = difference.stream().sorted(Comparator.comparingInt(Integer::intValue)).collect(Collectors.toList());
        List<Integer> blueList = blueSet.stream().sorted(Comparator.comparingInt(Integer::intValue)).collect(Collectors.toList());
        System.out.println("已存在:" + JSON.toJSONString(exitList));
        System.out.println("不存在:" + JSON.toJSONString(notExitList));
        System.out.println(JSON.toJSONString(blueList));
        Map<String,List<Integer>> result = new HashMap<>();
        result.put("exitList",exitList);
        result.put("notExitList",notExitList);
        result.put("blueList",blueList);
        return result;
    }
}
